package org.lc.stk.service.bank.impl;

import org.lc.stk.model.banks.Bank;

import java.util.List;
import java.util.stream.Collectors;

import org.lc.stk.dao.bank.CourseQuestionBankRepository;
import org.lc.stk.model.banks.CourseQuestionBank;
import org.lc.stk.model.course.Course;
import org.lc.stk.model.question.attrs.DifficultySchema;
import org.lc.stk.model.question.attrs.QuestionType;
import org.lc.stk.service.bank.CourseQuestionBankService;
import org.lc.stk.service.course.CourseService;
import org.lc.stk.service.exception.BusinessException;
import org.lc.stk.model.paper.attr.PaperTemplate;
import org.lc.stk.web.dto.bank.CourseQuestionBankDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.lc.stk.service.paper.PaperTemplateService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CourseQuestionBankServiceImpl implements CourseQuestionBankService {

    @Autowired
    private CourseQuestionBankRepository bankRepository;

    @Autowired
    private CourseService courseService;

    @Autowired
    private PaperTemplateService paperTemplateService;

    @Override
    @Transactional
    public CourseQuestionBank create(CourseQuestionBankDTO dto) {
        // 验证课程存在
        Course course = courseService.findById(dto.getCourseId());
        if (course == null) {
            throw new BusinessException("课程不存在");
        }

        // 验证名称是否重复
        if (bankRepository.existsByNameAndCourseIdAndIdNot(dto.getName(), dto.getCourseId(), null)) {
            throw new BusinessException("该课程下已存在同名题库");
        }

        CourseQuestionBank bank = new CourseQuestionBank();
        bank.setName(dto.getName());
        bank.setState(dto.getState() == 1 ? Bank.BankState.ACTIVE : Bank.BankState.INACTIVE);
        bank.setCourse(course);

        if (dto.getQuestionTypeIds() != null) {
            List<QuestionType> questionTypes = dto.getQuestionTypeIds().stream()
                .map(this::getQuestionType)
                .collect(Collectors.toList());
            bank.setQuestionTypes(questionTypes);
        }

        if (dto.getDifficultySchemaId() != null) {
            DifficultySchema schema = getDifficultySchema(dto.getDifficultySchemaId());
            bank.setDifficultySchema(schema);
        }

        return bankRepository.save(bank);
    }

    @Override
    @Transactional
    public CourseQuestionBank update(Integer id, CourseQuestionBankDTO dto) {
        CourseQuestionBank bank = getById(id);
        if (bank == null) {
            throw new BusinessException("题库不存在");
        }

        // 验证课程存在
        Course course = courseService.findById(dto.getCourseId());
        if (course == null) {
            throw new BusinessException("课程不存在");
        }

        // 验证名称是否重复
        if (bankRepository.existsByNameAndCourseIdAndIdNot(dto.getName(), dto.getCourseId(), id)) {
            throw new BusinessException("该课程下已存在同名题库");
        }

        bank.setName(dto.getName());
        bank.setState(dto.getState() == 1 ? Bank.BankState.ACTIVE : Bank.BankState.INACTIVE);
        bank.setCourse(course);

        if (dto.getQuestionTypeIds() != null) {
            List<QuestionType> questionTypes = dto.getQuestionTypeIds().stream()
                .map(this::getQuestionType)
                .collect(Collectors.toList());
            bank.setQuestionTypes(questionTypes);
        }

        if (dto.getDifficultySchemaId() != null) {
            DifficultySchema schema = getDifficultySchema(dto.getDifficultySchemaId());
            bank.setDifficultySchema(schema);
        }

        return bankRepository.save(bank);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        CourseQuestionBank bank = getById(id);
        if (bank == null) {
            throw new BusinessException("题库不存在");
        }
        
        // TODO 是否需要做一下验证能否停用
        
        bank.setState(Bank.BankState.INACTIVE); // 停用题库
        bankRepository.save(bank);
    }

    @Override
    public CourseQuestionBank getById(Integer id) {
        return bankRepository.findById(id)
            .orElseThrow(() -> new BusinessException("题库不存在"));
    }

    @Override
    public List<CourseQuestionBank> listByCourse(Integer courseId) {
        return bankRepository.findByCourseId(courseId);
    }

    @Override
    public Page<CourseQuestionBank> query(
        Integer courseId, 
        String name, 
        Integer state, 
        Pageable pageable
    ) {
        return bankRepository.findByConditions(courseId, name, state, pageable);
    }

    @Override
    public boolean isNameExists(String name, Integer excludeId, Integer courseId) {
        return bankRepository.existsByNameAndCourseIdAndIdNot(name, courseId, excludeId);
    }

    private QuestionType getQuestionType(Integer id) {
        // TODO: 从QuestionTypeService获取题型
        throw new UnsupportedOperationException("Not implemented");
    }

    private DifficultySchema getDifficultySchema(Integer id) {
        // TODO: 从DifficultySchemaService获取难度方案
        throw new UnsupportedOperationException("Not implemented");
    }
}
